{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Widget related imports\n",
    "import ipywidgets as widgets\n",
    "from IPython.display import display, clear_output, Javascript\n",
    "from traitlets import Unicode\n",
    "\n",
    "# nbconvert related imports\n",
    "from nbconvert import get_export_names, export, get_exporter\n",
    "from nbconvert.writers import FilesWriter\n",
    "from nbformat import read, NO_CONVERT\n",
    "from nbconvert.utils.exceptions import ConversionException"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This notebook shows a really roundabout way to get the name of the notebook file using widgets.  The true purpose of this demo is to demonstrate how Javascript and Python widget models are related by `id`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create a text Widget without displaying it.  The widget will be used to store the notebook's name which is otherwise only available in the front-end."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "notebook_name = widgets.Text()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Get the current notebook's name by pushing JavaScript to the browser that sets the notebook name in a string widget."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/javascript": [
       "IPython.notebook.kernel.widget_manager.get_model('864e0df9154c43e4919f60f8d4937d61').then(function(model) {\n",
       "    model.set('value', IPython.notebook.notebook_name);\n",
       "    model.save();\n",
       "});\n"
      ],
      "text/plain": [
       "<IPython.core.display.Javascript object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "js = \"\"\"IPython.notebook.kernel.widget_manager.get_model('%s').then(function(model) {\n",
    "    model.set('value', IPython.notebook.notebook_name);\n",
    "    model.save();\n",
    "});\n",
    "\"\"\" % notebook_name.model_id\n",
    "display(Javascript(data=js))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "''"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "filename = notebook_name.value\n",
    "filename"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create the widget that will allow the user to Export the current notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "exporter_names = widgets.Dropdown(options=get_export_names(), value='html')\n",
    "export_button = widgets.Button(description=\"Export\")\n",
    "download_link = widgets.HTML(visible=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Export the notebook when the export button is clicked."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "file_writer = FilesWriter()\n",
    "\n",
    "def export_nb(name, nb):\n",
    "    \n",
    "    # Get a unique key for the notebook and set it in the resources object.\n",
    "    notebook_name = name[:name.rfind('.')]\n",
    "    resources = {}\n",
    "    resources['unique_key'] = notebook_name\n",
    "    resources['output_files_dir'] = '%s_files' % notebook_name\n",
    "\n",
    "    # Try to export\n",
    "    try:\n",
    "        output, resources = export(get_exporter(exporter_names.value), nb)\n",
    "    except ConversionException as e:\n",
    "        download_link.value = \"<br>Could not export notebook!\"\n",
    "    else:\n",
    "        write_results = file_writer.write(output, resources, notebook_name=notebook_name)\n",
    "    \n",
    "        download_link.value = \"<br>Results: <a href='files/{filename}'><i>\\\"{filename}\\\"</i></a>\".format(filename=write_results)\n",
    "        download_link.visible = True\n",
    "        \n",
    "def handle_export(widget):\n",
    "    with open(filename, 'r') as f:\n",
    "        export_nb(filename, read(f, NO_CONVERT))\n",
    "        \n",
    "export_button.on_click(handle_export)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Display the controls."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "06f70e628bac446c85e923efe86af7a6",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Dropdown(index=2, options=('asciidoc', 'custom', 'html', 'latex', 'markdown', 'notebook', 'pdf', 'python', 'rs…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "73227a7c8398477bbf0dab447d80a7c0",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Button(description='Export', style=ButtonStyle())"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "74460f230be743bba556876b30d24852",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HTML(value='')"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "display(exporter_names, export_button, download_link)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {
     "064ba41bab5a4878a177a98c2da82adc": {
      "model_module": "@jupyter-widgets/base",
      "model_module_version": "1.0.0",
      "model_name": "LayoutModel",
      "state": {}
     },
     "06f70e628bac446c85e923efe86af7a6": {
      "model_module": "@jupyter-widgets/controls",
      "model_module_version": "1.2.0",
      "model_name": "DropdownModel",
      "state": {
       "_options_labels": [
        "asciidoc",
        "custom",
        "html",
        "latex",
        "markdown",
        "notebook",
        "pdf",
        "python",
        "rst",
        "script",
        "slides"
       ],
       "index": 2,
       "layout": "IPY_MODEL_ddc0a1d234f04a7691faf1c4debd8328",
       "style": "IPY_MODEL_3b798efd1f774ae08a39aa7f9a02d98a"
      }
     },
     "1c6f467abc8a404cbc34a7d80c5eaeed": {
      "model_module": "@jupyter-widgets/controls",
      "model_module_version": "1.2.0",
      "model_name": "ButtonStyleModel",
      "state": {}
     },
     "2f94502793db4e30a226e49cbeab3ce3": {
      "model_module": "@jupyter-widgets/base",
      "model_module_version": "1.0.0",
      "model_name": "LayoutModel",
      "state": {}
     },
     "3b798efd1f774ae08a39aa7f9a02d98a": {
      "model_module": "@jupyter-widgets/controls",
      "model_module_version": "1.2.0",
      "model_name": "DescriptionStyleModel",
      "state": {
       "description_width": ""
      }
     },
     "73227a7c8398477bbf0dab447d80a7c0": {
      "model_module": "@jupyter-widgets/controls",
      "model_module_version": "1.2.0",
      "model_name": "ButtonModel",
      "state": {
       "description": "Export",
       "layout": "IPY_MODEL_f077dd852e084250babc32636391bb17",
       "style": "IPY_MODEL_1c6f467abc8a404cbc34a7d80c5eaeed"
      }
     },
     "74460f230be743bba556876b30d24852": {
      "model_module": "@jupyter-widgets/controls",
      "model_module_version": "1.2.0",
      "model_name": "HTMLModel",
      "state": {
       "layout": "IPY_MODEL_064ba41bab5a4878a177a98c2da82adc",
       "style": "IPY_MODEL_d1095561917a4a59a28b4f2e250767ca"
      }
     },
     "78d9bd344a9a448491d2c7663e490497": {
      "model_module": "@jupyter-widgets/controls",
      "model_module_version": "1.2.0",
      "model_name": "DescriptionStyleModel",
      "state": {
       "description_width": ""
      }
     },
     "864e0df9154c43e4919f60f8d4937d61": {
      "model_module": "@jupyter-widgets/controls",
      "model_module_version": "1.2.0",
      "model_name": "TextModel",
      "state": {
       "layout": "IPY_MODEL_2f94502793db4e30a226e49cbeab3ce3",
       "style": "IPY_MODEL_78d9bd344a9a448491d2c7663e490497",
       "value": "Export As (nbconvert).ipynb"
      }
     },
     "d1095561917a4a59a28b4f2e250767ca": {
      "model_module": "@jupyter-widgets/controls",
      "model_module_version": "1.2.0",
      "model_name": "DescriptionStyleModel",
      "state": {
       "description_width": ""
      }
     },
     "ddc0a1d234f04a7691faf1c4debd8328": {
      "model_module": "@jupyter-widgets/base",
      "model_module_version": "1.0.0",
      "model_name": "LayoutModel",
      "state": {}
     },
     "f077dd852e084250babc32636391bb17": {
      "model_module": "@jupyter-widgets/base",
      "model_module_version": "1.0.0",
      "model_name": "LayoutModel",
      "state": {}
     }
    },
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
